#!/bin/python3
# markdown文件 内容目录生成
# 阿诏 2022/7/26

import os
import sys

def DeleteOldContext(contest_list = ['']):
    is_context = False
    index_context = -1
    line_count = 0

    for pos_line in contest_list:
        if pos_line.find("# 目录") >= 0:
            index_context = contest_list.index(pos_line)
            is_context = True
            break

    if is_context:
        temp_index = index_context + 1
        while temp_index < len(contest_list):
            temp_str = contest_list[temp_index].strip()
            if temp_str.find('#') == 0 and temp_str.find("# ") >= 0:
                break
            else:
                temp_index += 1
        line_count = temp_index - index_context

        for i in range(line_count):
            contest_list.pop(index_context)

    return contest_list


def JudgeContest(a_string = ''):
    a_string = a_string.strip()

    indx = a_string.find("](")
    if a_string[0] == '[' and indx > 1 and a_string[-1] == ')':
        a_string = a_string[1 : indx]
        pass

    return a_string



def GetFormatTitle(contest, title_list, section_no):
    level = 0
    while contest[level] == "#":
        level += 1

    name_from = level
    name_end = level
    while contest[name_end] not in "<\r\n":
        name_end += 1

    blank_str = ""
    sign_str = "#"
    for i in range(name_from - 1):
        blank_str += "  "
        sign_str += "#"
    
    blank_str = blank_str[2: ]

    title_name = JudgeContest(contest[name_from : name_end])
    section_str = "section.{0}".format(section_no)
    context_str = "context.{0}".format(section_no)

    title_list.append("%s- [%s](#%s)<a name=\"%s\"> </a>" % (blank_str, title_name, section_str, context_str))

    #return ("%s %s" % (sign_str, title_name))
    #return ("%s %s<a name=\"%s\"></a>" % (sign_str, title_name, section_str))
    return ("%s [%s](#%s)<a name=\"%s\"> </a>" % (sign_str, title_name, context_str, section_str))


def DoGenMarkdownToc(g_work_path, g_file_name, g_crlf):
    os.chdir(g_work_path)
    section_num = 0

    # 获取内容
    fd = open(g_file_name, "r", encoding='utf-8')

    contest_list = fd.readlines()
    if contest_list[0][-2:] != g_crlf:
        g_crlf = contest_list[0][-1]
    fd.close()

    # 删除已有目录
    contest_list = DeleteOldContext(contest_list)

    # 获取标题
    title_list = []
    is_comment = False
    for contest in contest_list[1: ]:
        temp = contest.lstrip()
        
        if temp.find("```") == 0:
            is_comment = bool(1 - is_comment)
        
        if (not is_comment) and len(temp) > 0 and temp[0] == "#":
            section_num += 1
            contest_list[contest_list.index(contest)] = GetFormatTitle(temp, title_list, section_num) + g_crlf
        pass

    # 输出新文件
    while contest_list[0] == "":
        contest_list.pop(0)
    # 删除旧目录
    # ind = 0
    # while ind < len(contest_list):
    #     if contest_list[ind].find("## 目录")

    fd = open(g_file_name, "w", encoding='utf-8')


    # 头部标题不设置超链接, 并且为一级标题
    head_str = contest_list.pop(0)
    head_str_l = head_str.find("[");
    head_str_r = head_str.find("](");
    fd.write(head_str[head_str_l + 1 : head_str_r] + g_crlf)

    fd.write("## 目录" + g_crlf)

    for title in title_list:
        fd.write(title + g_crlf)

    fd.write('------------------------------------------------  ' + g_crlf)
    fd.writelines(contest_list)

    fd.close()
    return

# 判断1个文件是不是md文件，是的话执行目录生成
# 注：readme.md不执行，readme文件名不区分大小写
# 
def mdtoc_JudgeOneFileThenDo(g_work_path, file_path, g_crlf):

    if os.path.isfile(file_path):
        file = os.path.basename(file_path)
        name, extension = os.path.splitext(file)
        if extension == ".md" and name.lower() != "readme":
            DoGenMarkdownToc(g_work_path, file_path, g_crlf)


# 文件夹下递归遍历md文件然后执行目录生成
# path保证是一个绝对路径，不能是相对路径或文件名
# 返回md文件列表
def mdtoc_RecurAndDo(g_work_path, dir_path, g_crlf):
    path_list = os.listdir(dir_path)    # 获取path目录下的文件夹和文件名
    
    for one in path_list:
        full_path = os.path.join(dir_path, one)
        if os.path.isdir(full_path):
            mdtoc_RecurAndDo(g_work_path, full_path, g_crlf)
        else:
            mdtoc_JudgeOneFileThenDo(g_work_path, full_path, g_crlf)

def mdtoc_entry(g_work_path, path, g_crlf):
    full_path = os.path.join(g_work_path, path)
    if os.path.isdir(full_path):
        print(full_path)
        mdtoc_RecurAndDo(g_work_path, full_path, g_crlf)
    else:
        name, extension = os.path.splitext(full_path)
        if extension == ".md":
            DoGenMarkdownToc(g_work_path, full_path, g_crlf)
        else:
            print("error: " + full_path + " is not a markdown file");

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    if len(sys.argv) == 3:
        g_work_path = sys.argv[1]
        g_file_name = sys.argv[2]
        if os.sep == '\\':
            g_crlf = "\r\n"
        else:
            g_crlf = "\n"

        # print("g_work_path: " + g_work_path)
        # print("g_file_name: " + g_file_name)
        # print("g_crlf: "      + g_crlf)

        mdtoc_entry(g_work_path, g_file_name, g_crlf)
    elif len(sys.argv) == 2 and sys.argv[1] == "--generate":
        if os.sep == '\\':
            # 生成mdtoc.bat
            print("generate mdtoc.bat -- start")
            fd = open("mdtoc.bat", "w", encoding='utf-8')
            file_name = os.getcwd() + "\\md_toc.py"
            print("echo python " + file_name + " %cd% %1 >> mdtoc.bat")
            fd.write("@echo off\r\n")
            fd.write("python " + file_name + " %cd% %1")
            fd.close()
            print("generate mdtoc.bat -- end")
        else:
             # 生成mdtoc.sh
            print("generate mdtoc.sh -- start")
            fd = open("mdtoc.sh", "w", encoding='utf-8')
            file_name = os.getcwd() + "/md_toc.py"
            print("echo python " + file_name + " $(pwd) $1 >> mdtoc.sh")
            fd.write("python3 " + file_name + " $(pwd) $1")
            fd.close()
            print("generate mdtoc.sh -- end")
        
        print ("cwd : %s" % os.getcwd())
    else:
        print("[param error]")







# See PyCharm help at https://www.jetbrains.com/help/pycharm/
